package com.inspector.app.di.location

import android.annotation.SuppressLint
import android.location.LocationListener
import android.location.LocationManager

/**
 * Android原生定位
 * @author CodeK 2024/6/14
 */
class GPSLocationInstance {

    @SuppressLint("MissingPermission")
    fun startLocation(locationManager: LocationManager?, minInterval: Long, minDistance: Float, locationListener: CustomLocationListener?) {
        val customLocationListener = locationListener ?: throw IllegalStateException("SystemLocationInstance 未设置定位回调")
        locationManager?.removeUpdates(customLocationListener)
        locationManager?.getProviders(true)?.forEach { provider ->
            if (LocationManager.GPS_PROVIDER == provider
                || LocationManager.NETWORK_PROVIDER == provider) {
                locationManager.requestLocationUpdates(provider, minInterval, minDistance, customLocationListener)
                locationManager.getLastKnownLocation(provider)?.let {
                    customLocationListener.onLocationChanged(it, true)
                }
            }
        }
    }

    fun stopLocation(locationManager: LocationManager?, locationListener: LocationListener?) {
        locationListener?.let { locationManager?.removeUpdates(it) }
    }


    companion object {
        val instance: GPSLocationInstance by lazy { GPSLocationInstance() }
    }
}
